package com.sun.umbrella.oauth2;

import com.google.gson.Gson;
import com.sun.umbrella.Constants;
import com.sun.umbrella.remote.RemoteService;
import com.sun.umbrella.session.ContextHolder;
import com.sun.umbrella.session.SessionContext;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Jay
 * @version v1.0
 * @description 认证
 * @date 2017-11-24 15:35
 */
@Slf4j
public class Oauth2AuthenticationFilter extends AuthenticatingFilter {


    @Autowired
    private ContextHolder contextHolder;


    @Autowired
    private RemoteService remoteService;

    /**
     * oauth2 authc code参数名
     */
    @Setter
    private String authcCodeParam = ResponseType.CODE.toString();

    /**
     * 失败访问的url
     */
    @Setter
    private String failureUrl;


    /**
     * 创建token
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String code = httpRequest.getParameter(authcCodeParam);
        return new Oauth2Token(code);
    }


    /**
     * 存储session信息
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            String principal = (String) subject.getPrincipal();
            SessionContext sessionContext = remoteService.getSessionContext(principal);
            contextHolder.initSessionContext(sessionContext);
        }
        return subject.isAuthenticated();
    }


    /**
     * 拒绝访问的时候
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        String error = request.getParameter("error");
        String errorDescription = request.getParameter("error_description");
        // 是否由前端跳转 (为了解决前后端分离出现的服务端无法跳转的情况)
        String redirectFront = ((HttpServletRequest) request).getHeader(Constants.REDIRECT_FRONT);

        if (!StringUtils.isEmpty(error)) {
            // 如果服务端返回了错误
            WebUtils.issueRedirect(request, response, failureUrl + "?error=" + error + "error_description=" + errorDescription);
            return false;
        }
        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated()) {
            // 如果不是携带了code的请求，那么直接将登陆的ur返回给客户端处理
            if (StringUtils.isEmpty(request.getParameter(authcCodeParam))) {
                // 如果在请求头内含有redirect_front，说明该请求由前端跳转
               if (!StringUtils.isEmpty(redirectFront) && Integer.valueOf(redirectFront) == 1) {
                    ((HttpServletResponse) response).setHeader("redirectUrl", this.getLoginUrl());
                    Oauth2Result result = new Oauth2Result();
                    result.setIsLogin(Boolean.FALSE);
                    result.setSuccess(Boolean.FALSE);
                    result.setDirectUrl(this.getLoginUrl());
                    response.getWriter().write(new Gson().toJson(result));
                } else {
                    // 如果用户没有身份验证，且没有auth code，则重定向到服务端授权
                    saveRequestAndRedirectToLogin(request, response);
                }
            }
        }
        // 如果是携带了code的请求，那么说明该请求正在进行oauth2的认证流程，那么使用code
        return executeLogin(request, response);
    }


    /**
     * 保存当前链接并跳转
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @Override
    protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String url = httpServletRequest.getHeader(Constants.REDIRECT_PAGE_URL);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        // 将请求头内的页面重定向地址写入session
        session.setAttribute(Constants.REDIRECT_PAGE_URL, url);
        // 设置重定向的接口地址 通过response返回
        Oauth2Result result = new Oauth2Result();
        result.setIsLogin(Boolean.FALSE);
        result.setSuccess(Boolean.FALSE);
        result.setDirectUrl(this.getLoginUrl());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(new Gson().toJson(result));
    }

    /**
     * 登陆认证成功后跳转到资源页面
     *
     * @param token
     * @param subject
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
                                     ServletResponse response) throws Exception {
        issueSuccessRedirect(request, response);
        return false;
    }

    /**
     * 登陆认证成功后跳转到资源页面
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        // 获取重定向的页面地址
        String fallbackUrl = (String) session.getAttribute(Constants.REDIRECT_PAGE_URL);
        WebUtils.redirectToSavedRequest(request, response, fallbackUrl);
    }


    /**
     * 登陆失败的回调
     *
     * @param token
     * @param ae
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request,
                                     ServletResponse response) {
        Subject subject = getSubject(request, response);
        if (subject.isAuthenticated() || subject.isRemembered()) {
            try {
                issueSuccessRedirect(request, response);
            } catch (Exception e) {
                log.error(this.getClass().getName(), e);
            }
        } else {
            try {
                WebUtils.issueRedirect(request, response, failureUrl);
            } catch (IOException e) {
                log.error(this.getClass().getName(), e);
            }
        }
        return false;
    }

    /**
     * 请求结束后清空业务session
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        contextHolder.resetContext();
    }
}
